<?php

namespace app\controller\adminapi;

use app\middleware\AuthComment;
use app\BaseController;
use app\model\Admin as ModelAdmin;
use throttling\ThrottlingFunnel;

use think\exception\ValidateException;
use think\facade\Cache;

/**
 * @api 管理员
 * @AuthComment loginModels ["Admin"]
 */
class Admin extends BaseController
{
    // 中间
    protected $middleware = [AuthComment::class];

    /**
     * @api 登陆
     * @desc 默认帐号admin<br/>默认密码123456<br/>
     * @param string $account 帐号
     * @param string $pswd
     * @AuthComment loginModels []
     */
    public function login($account = '', $pswd = '')
    {
        $thro = new ThrottlingFunnel('AdminLogin:' . request()->ip(), [
            'out_dely' => 30,
            'max_count' => 10,
        ]);
        if (!$thro->inc()) {
            return failed('操作太频繁，请稍后再试');
        }

        $admin = ModelAdmin::where('account', $account)->find();
        if (!$admin) return failed('管理员不存在');
        if (!$admin->checkPswd($pswd)) return failed('密码错误');

        $admin->updateLoginInfo(); // 记录登陆信息

        $tokenApp = ModelAdmin::getTokenApp();
        $tokenApp->clear($admin['id']); // 有这一行就是单点登录

        $tokenApp->saveData($admin['id'], $admin); // 保存管理员数据到Token中
        $token = $tokenApp->create($admin['id']);

        return success(['token' => $token]);
    }

    /**
     * @api 获取管理员详情
     * @desc 使用全局token，无需传参
     */
    public function detail()
    {
        return success($this->request->AuthComment->getLoginModel('Admin'));
    }

    /**
     * @api 修改密码
     * @param string $pswd 新密码
     */
    public function changePswd($pswd = '')
    {
        $this->validate(['pswd' => $pswd], ['pswd|密码' => 'require|min:6|alphaDash']);

        $admin = $this->request->AuthComment->getLoginModel('Admin');
        $admin->savePswd($pswd);
        return success();
    }

    /**
     * @api 获取所有模型信息
     */
    public function getModels()
    {
        $modelClasses = parseReflectionNamespaceClasses(
            app_path('model'),
            'app\model\\'
        );

        $result = [];
        foreach ($modelClasses as $modelRef) {
            try {
                $className = $modelRef->getName();
                $model = new $className;

                // 名称
                $name = $modelRef->getShortName();
                $alias = property_exists($model, 'modelAlias') ? $model::$modelAlias : $modelRef->getShortName();

                // 表字段
                $fields = array_values($model->getFields());

                // 枚举
                $enums = [];
                $constantsRef = $modelRef->getReflectionConstants();
                foreach ($constantsRef as $constant) {
                    $constantValue = $constant->getValue();
                    if (!is_array($constantValue)) continue;

                    $constantName = $constant->getName();

                    $constantCnName = '';
                    foreach (parseReflectionComment($constant->getDocComment()) as $docLine) {
                        if (($docLine[0] ?? '') === 'var') {
                            $constantCnName = $docLine[2];
                            break;
                        }
                    }

                    $enums[] = [
                        'name' => $constantName,
                        'alias' => $constantCnName,
                        'value' => $constantValue,
                    ];
                }

                $result[] = compact('name', 'alias', 'fields', 'enums');
            } catch (\Exception $e) {
            }
        }

        return success($result);
    }
}
